package com.ccplay.dataservice.web.payment;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ccplay.dataservice.web.BaseAction;
import com.google.gson.reflect.TypeToken;
import com.oxygen.constants.Constant;
import com.oxygen.dto.ApiFinalResponse;
import com.oxygen.enums.ApiMethodEnum;
import com.oxygen.enums.ApiMsgEnum;
import com.oxygen.util.JsonUtil;

/**
 * 支付
 * 
 * @author kevin
 * 
 */
@Controller
@RequestMapping(value = { "/api/v2/payment" })
public class PaymentAction extends BaseAction {

	/**
	 * 财富通回调
	 * 
	 * @param req
	 * @param rsp
	 * @return
	 */
	@RequestMapping(value = { "/tenpayCallback/{paymentId}", "/tenpayCallback/{paymentId}/" })
	public void tenpayCallback(@PathVariable String paymentId, HttpServletRequest req, HttpServletResponse rsp) {
		Map<String, String> reqParam = getAllRequestParam(req);
		String returnParam = JsonUtil.objectToJson(reqParam);
		// 打印请求报文
		loger.info(reqParam);
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put(Constant.API_KEY, "android_payment_sdk");
		appendMap.put("paymentDesc", returnParam);
		appendMap.put("paymentChannelCode", "tenpay");
		appendMap.put("transaction_no", reqParam.get("sp_billno"));
		appendMap.put("paymentId", paymentId);
		appendMap.put("paymentTransactionNo", reqParam.get("transaction_id"));
		if ("0".equals(reqParam.get("pay_result").trim())) {
			appendMap.put("status", "paid");
		} else {
			appendMap.put("status", "pay_fail");
		}
		String json = this.callApi(ApiMethodEnum.PAYMENT_PAYMENTCALLBACK, appendMap);
		Type type = new TypeToken<Map<String, ApiFinalResponse<Object>>>() {
		}.getType();
		Map<String, ApiFinalResponse<Object>> tempMap = JsonUtil.jsonToObject(json, type);
		if (tempMap != null && tempMap.get(ApiMethodEnum.PAYMENT_PAYMENTCALLBACK.getCode()) != null) {
			String code = tempMap.get(ApiMethodEnum.PAYMENT_PAYMENTCALLBACK.getCode()).getCode();
			if (ApiMsgEnum.SUCCESS.getCode().equals(code)) {
				this.outputJson("success", rsp);
			}
		}
		this.outputJson("fail", rsp);
	}

	/**
	 * 获取请求参数中所有的信息
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				// 在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				// System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> parseXmltoMap(HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		InputStream inputStream = request.getInputStream();
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();
		// 遍历所有子节点
		if (elementList == null || elementList.size() == 0) {
			return null;
		}
		for (Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		// 释放资源
		inputStream.close();
		inputStream = null;
		return map;
	}
}
